package com.hbl.cgs.cgsagent.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.text.DecimalFormat;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ExecutionException;

public class QuotationProducer {
    private static final int MSG_SIZE = 100;
    private static final String TOPIC = "stock-quotation2";
    private static final String BROKER_LIST = "localhost:9092";
    private static KafkaProducer<String, String> producer = null;
    static {
        Properties properties = initConfig();
        producer = new KafkaProducer<String, String>(properties);
    }

    private static Properties initConfig() {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        return properties;
    }

    public static StockQuotationInfo createQuotationInfo() {
        StockQuotationInfo stock = new StockQuotationInfo();
        Random r = new Random();
        Integer stockCode = 600100 + r.nextInt(10);
        float random = (float) Math.random();
        if (random / 2 < 0.5) {
            random = - random;
        }
        DecimalFormat decimalFormat = new DecimalFormat(".00");
        stock.setCurrentPrice(Float.valueOf(decimalFormat.format(11 + random)));
        stock.setPreClosePrice(11.8f);
        stock.setLowPrice(10.5f);
        stock.setHighPrice(12.4f);
        stock.setStockName("stock-" + stockCode);
        return stock;
    }

    public static void main(String[] args) {
        ProducerRecord<String, String> record = null;
        StockQuotationInfo quotationInfo = null;
        try {
            int num = 0;
            for (int i = 0; i < MSG_SIZE; i++) {
                quotationInfo = createQuotationInfo();
                System.out.println(quotationInfo.toString());
                record = new ProducerRecord<>(TOPIC, 2,
                        quotationInfo.getStockCode(), quotationInfo.toString());
                System.out.println("producer");
                producer.send(record).get();
                if (num++ % 10 == 0) {
                    Thread.sleep(1000);
                }
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            producer.close();
        }
    }
}
